<?php
declare(strict_types=1);

namespace WebApp\lib\util;

use Throwable;
use txz\common\dao\models\base\DaoBase;
use WebApp\lib\proxy\HandlerInterface;

/**
 * Class Proxy
 * @package WebApp\lib\util
 */
class Proxy
{
    /**
     * @param $obj
     * @param HandlerInterface $handler
     * @return mixed
     */
    public static function newProxyInstance($obj, $handler = null)
    {
        return new class ($handler, $obj){
            private $handler = null;
            /**
             * @var DaoBase
             */
            private $obj = null;

            /**
             *  constructor.
             * @param HandlerInterface $handler
             * @param $obj
             */
            public function __construct($handler, $obj)
            {
                $this->handler = $handler;
                $this->obj = $obj;
            }

            /**
             * @param $method
             * @param $arguments
             * @return bool|mixed
             */
            public function __call($method, $arguments)
            {
                try {
                    $res = call_user_func([$this->obj, $method], ...$arguments);
                } catch (Throwable $e) {
                    Util::logE($e->getMessage());
                    return $this->obj->pdoException($e);
                }

                return $res;
            }
        };
    }
}
